import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import router from '../router/index'

const http: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8888',
  timeout: 5000
})
http.interceptors.request.use((request: AxiosRequestConfig): AxiosRequestConfig => {
  const token = sessionStorage.getItem('token')
  if (token) {
    //每次请求都把token携带过去
    request.headers.token = token
  }
  return request
}, (error: any) => {
  return Promise.reject(error)
})
http.interceptors.response.use((response: AxiosResponse): AxiosResponse | Promise<never> => {
  const res = response.data
  //与后端约定，0：请求成功
  if (res.code === 0) {
      return res
  }
  if (res.code === 250004) {
    sessionStorage.clear()
    console.log('token失效')
    router.replace({ path: '/' })
  }
  return res
}, (error: any) => {
  // console.log('响应发生错误：' + error.response.data);
  //如果后端返回了401用户未登录，则跳转到登录界面
  console.log(error)
  // if (error.response.code === 401) {
  //   sessionStorage.clear()
  //   console.log('token失效');
  //   router.replace({ path: '/' })
  // }
  return Promise.reject(error)
})

export default http